<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>
    &nbsp; &nbsp; &nbsp;
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-tree
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="edit(data)">
            修改
          </el-button>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit(data)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDataList,
  deleteCategory,
  addCategory,
  getCategoryByCatId,
  updateCategoryByCategory,
  updateCategory,
} from "@/api/product/category/category";
export default {
  data() {
    return {
      pCid: [],
      draggable: false,
      updateNodes: [],
      maxLevel: 0,
      title: "",
      dialogType: "", // edit,add
      data: [],
      expandKey: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      loading: false,
      dialogVisible: false,
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: "",
        productUnit: "",
      },
    };
  },
  methods: {
    batchSave() {
      updateCategory(this.updateNodes).then((response) => {
        if (response.code == 0) {
          this.$message({
            message: "菜单顺序修改成功",
            type: "success",
          });
          // 刷新
          this.getMenus();
          // 设置需要默认展开的菜单
          this.expandKey = [this.pCid];
          this.updateNodes = [];
          this.maxLevel = 0;
          // this.pCid = 0;
        }
      });
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("tree drop: ", dropNode.label, dropType);

      // 当前节点最新的父节点
      let pCid = 0;
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);

      // 当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          // 如果遍历的是当前正在拖拽的节点
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            // 当前节点的层级发生变化
            catLevel = dropNode.level;

            // 修改子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }

      console.log("updateNodes", this.updateNodes);
    },
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      // 被拖动的当前节点以及所在的父节点总层数不能大于3
      console.log(draggingNode, dropNode, type);
      this.countLevel(draggingNode.data);

      console.log("最大节点深度", this.maxLevel);
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;

      if (type == "inner") {
        return deep + dropNode.level <= 3;
      }
      return deep + dropNode.parent.level <= 3;
    },

    countLevel(node) {
      // 找到所有节点，求出最大深度
      if (node.children != null && node.children.length > 0) {
        console.log("node.childNodes:", node.children, node.children.length);
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].level > this.maxLevel) {
            this.maxLevel = node.children[i].level;
          }
          this.countLevel(node.children[i]);
        }
      }
    },

    submit() {
      if (this.dialogType == "add") {
        this.addCategory();
      }
      if (this.dialogType == "edit") {
        this.editCategroy();
      }
    },
    editCategroy() {
      // var { catId, name, icon, productUnit } = this.category;
      updateCategoryByCategory(this.category).then((response) => {
        if (response.code == 0) {
          this.$message({
            message: "菜单保存成功",
            type: "success",
          });
          // 关闭对话框
          this.dialogVisible = false;
          // 刷新
          this.getMenus();
          // 设置需要默认展开的菜单
          this.expandKey = [this.category.parentCid];
        }
      });
    },
    // 修改菜单名称
    edit(data) {
      this.title = "修改";
      this.dialogVisible = true;
      this.dialogType = "edit";

      // 发送请求获取当前节点最新的数据
      getCategoryByCatId(data.catId).then((response) => {
        if (response.code == 0) {
          console.log("回显的数据：", response, data);
          this.category.name = response.data.name;
          this.category.catId = response.data.catId;
          this.category.icon = response.data.icon;
          this.category.productUnit = response.data.productUnit;
          this.category.parentCid = response.data.parentCid;
          this.category.catLevel = response.data.catLevel;
          this.category.sort = response.data.sort;
          this.category.showStatus = response.data.showStatus;
        }
      });
    },
    // 添加三级分类的方法
    addCategory() {
      console.log("三级分类", this.category);
      addCategory(this.category).then((response) => {
        if (response.code == 0) {
          this.$message({
            message: "菜单保存成功",
            type: "success",
          });
          // 关闭对话框
          this.dialogVisible = false;
          // 刷新
          this.getMenus();
          // 设置需要默认展开的菜单
          this.expandKey = [this.category.parentCid];
        }
      });
    },
    getMenus() {
      this.loading = true;
      getDataList().then((response) => {
        // 假设接口返回的数据结构为 { code: 200, data: [...] }
        if (response.code === 0) {
          this.data = response.data;
        } else {
          console.error("获取菜单数据失败:", response.message);
        }
      });
    },
    append(data) {
      this.title = "添加";
      this.dialogVisible = true;
      this.dialogType = "add";
      console.log("data", data);
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.name = "";
      this.category.catId = null;
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.sort = 0;
      this.category.showStatus = 1;
    },

    remove(node, data) {
      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        var ids = [data.catId];
        deleteCategory(ids)
          .then((response) => {
            // 假设接口返回的数据结构为 { code: 0, message: '操作成功' }
            if (response.code === 0) {
              this.$message({
                message: "菜单删除成功",
                type: "success",
              });
              this.getMenus();
              // 设置需要默认展开的菜单
              this.expandKey = [node.parent.data.catId];
              console.log("删除成功", node, data);
            } else {
              this.$message({
                message: response.message || "删除失败",
                type: "error",
              });
              console.error("删除失败:", response.message);
            }
          })
          .catch((error) => {
            this.$message({
              message: "网络错误，请重试",
              type: "error",
            });
            console.error("删除请求异常:", error);
          });
      });
    },
  },
  created() {
    this.getMenus();
  }
};
</script>

<style>
</style>
